package com.example.everying.task;

import com.example.everying.framework.websocket.service.WebSocketChatService;
import com.example.everying.framework.websocket.utils.WebSocketRedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

@Slf4j
@Component
public class WebSocketHeartbeatTask {

    // 心跳检测间隔（毫秒）
    private static final long HEARTBEAT_INTERVAL = 30000;
    private static final long HEARTBEAT_INTERVAL5 = 5000;
    // 超时阈值（毫秒）
    private static final long TIMEOUT_THRESHOLD = 60;
    @Autowired
    private WebSocketChatService webSocketChatService;
    @Autowired
    private WebSocketRedisUtil redisUtils;


    @Scheduled(fixedRate = HEARTBEAT_INTERVAL) // 每30秒执行一次
    public void checkConnections() {
        try {
            // 1. 获取所有活跃会话
            Map<String, Long> activeSessions = redisUtils.getActiveSessions();
            long currentTime = System.currentTimeMillis() / 1000;

            // 2. 检查超时会话
            activeSessions.forEach((userId, lastActive) -> {
                log.debug(" 用户: {}, 最后活跃时间: {}", userId, lastActive);
                long timeDifference = currentTime - lastActive;
                log.debug("系统时间戳：{} 上次活跃时间：{} 差值：{} ", currentTime, lastActive, timeDifference);
                if (timeDifference > TIMEOUT_THRESHOLD) {
                    log.info(" 检测到超时会话: {}", userId);
                    // 这里可以添加额外的连接关闭逻辑
                    webSocketChatService.onClose(userId);
                    // 删除用户记录
                    redisUtils.cleanUserRecord(userId);
                }
            });

            // 3. 日志监控
            log.debug(" 当前活跃会话数: {}", activeSessions.size());
        } catch (Exception e) {
            log.error(" 心跳检测异常", e);
        }
    }
}
